package com.kime.shiro.base.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: JiangYi
 * @Date: 2022-03-13 18:46:05
 * @Description: 自定义 Realm 实现，将认证、授权数据的来源转为数据库的实现
 */
public class CustomerRealm extends AuthorizingRealm {

    // 授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("==============");
        return null;
    }

    // 认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 在 token 中获取用户名
        String principal = (String) authenticationToken.getPrincipal();
        System.out.println(principal);
        // 根据身份信息使用 jdbc mybatis 查询相关数据库
        if ("zhangsan".equals(principal)) {
            /*
            参数1：代表返回数据库中正确的用户名
            参数2：代表返回数据库中正确的密码
            参数3：代表提供当前 Realm 的名字，直接调父类 this.getName();
             */
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("zhangsan", "123", this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
